package com.example.sharesinfo.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sharesinfo.R;
import com.example.sharesinfo.adapter.MyPagerAdapter;
import com.example.sharesinfo.base.BaseUIActivity;
import com.example.sharesinfo.bean.SearchStocksBean;
import com.example.sharesinfo.entity.Constants;
import com.example.sharesinfo.fragment.index.RecommendFragment;
import com.example.sharesinfo.fragment.search.SearchInformationFragment;
import com.example.sharesinfo.fragment.search.SearchStockFragment;
import com.example.sharesinfo.fragment.search.SearchUserFragment;
import com.example.sharesinfo.model.SearchNewsModel;
import com.example.sharesinfo.model.SearchStockModel;
import com.example.sharesinfo.model.SearchUsersModel;
import com.example.sharesinfo.utils.LogUtils;
import com.example.sharesinfo.utils.OkHttpUtils;
import com.example.sharesinfo.utils.SpUtils;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

public class SearchActivity extends BaseUIActivity implements View.OnClickListener {
    private static final int SearchStocksSuccess = 1001;
    private static final int SearchStocksFailed = 1002;
    private static final int SearchUsersSuccess = 1003;
    private static final int SearchUsersFailed = 1004;
    private static final int SearchNewsSuccess = 1005;
    private static final int SearchNewsFailed = 1006;
    private ImageButton ib_back;
    private List<Fragment> fragments = new ArrayList<>();
    private List<String> titles = new ArrayList<>();
    private SearchStockFragment mStockFragment = new SearchStockFragment();
    private SearchInformationFragment mInformationFragment = new SearchInformationFragment();
    private SearchUserFragment mUserFragment = new SearchUserFragment();
    private TabLayout mTableLayout;
    private ViewPager mViewPager;
    private EditText et_search;
    private TextView tv_search_button;
    //股票搜索
    public List<SearchStockModel> stockList = new ArrayList<>();
    //用户搜索
    private List<SearchUsersModel> userList = new ArrayList<>();
    //SearchNewsModel
    private List<SearchNewsModel> newsList = new ArrayList<>();
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case SearchStocksSuccess:
                    JSONArray array = (JSONArray) msg.obj;
                    if (array.length() > 0) {
                        for (int i = 0; i < array.length(); i++) {
                            try {
                                JSONObject object = array.getJSONObject(i);
                                SearchStockModel model = new SearchStockModel();
                                model.setStockName(object.getString("StockName"));
                                model.setStockCode(object.getString("StockCode"));
                                stockList.add(model);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        mStockFragment.mStockAdapter.mList = stockList;
                        mStockFragment.mStockAdapter.notifyDataSetChanged();
                    }
                    break;

                case SearchUsersSuccess:
                    JSONArray array1 = (JSONArray) msg.obj;
                    if (array1.length() > 0) {
                        for (int i = 0; i < array1.length(); i++) {
                            try {
                                JSONObject object = array1.getJSONObject(i);
                                SearchUsersModel model = new SearchUsersModel();
                                model.setId(Integer.parseInt(object.getString("Id")));
                                model.setImageUrl(object.getString("ImageUrl"));
                                model.setUsername(object.getString("Username"));
                                userList.add(model);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        mUserFragment.mAdapter.mList = userList;
                        mUserFragment.mAdapter.notifyDataSetChanged();
                    }
                    break;
                case SearchNewsSuccess:
                    JSONArray array2 = (JSONArray) msg.obj;
                    if (array2.length() > 0) {
                        for (int i = 0; i < array2.length(); i++) {
                            try {
                                JSONObject object = array2.getJSONObject(i);
                                SearchNewsModel model = new SearchNewsModel();
                                model.setId(object.getString("Id"));
                                model.setTitle(object.getString("Title"));
                                model.setContent(object.getString("Content"));
                                model.setSource(object.getString("Source"));
                                model.setIssueTime(object.getString("IssueTime"));
                                newsList.add(model);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        mInformationFragment.mInfoAdapter.mList = newsList;
                        mInformationFragment.mInfoAdapter.notifyDataSetChanged();
                    }
                    break;
                case SearchStocksFailed:
                case SearchUsersFailed:
                case SearchNewsFailed:
                    Toast.makeText(SearchActivity.this, "获取数据失败", Toast.LENGTH_SHORT).show();
                    break;


            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initData();
        initView();
    }

    private void initView() {
        ib_back= findViewById(R.id.ib_back);
        ib_back.setOnClickListener(this);
        tv_search_button = findViewById(R.id.tv_search_button);
        tv_search_button.setOnClickListener(this);
        et_search = findViewById(R.id.et_msearch);
        mTableLayout = findViewById(R.id.tl_tabs);
        mTableLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        mViewPager = findViewById(R.id.vp_view);
        mViewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(), this, fragments, titles));
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                LogUtils.i("监听onPageSelected" + position);
                //监听改变
                switch (position) {
                    case 0:
                        et_search.setTag("0");
                        et_search.setText("");
                        et_search.setHint("股票代码/名称");
                        break;
                    case 1:
                        et_search.setTag("1");
                        et_search.setText("");
                        et_search.setHint("资讯热词/关键字");
                        break;
                    case 2:
                        et_search.setTag("2");
                        et_search.setText("");
                        et_search.setHint("用户名称");
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        mTableLayout.setupWithViewPager(mViewPager);//此方法就是让tablayout和ViewPager联动
    }

    private void initData() {

        fragments.add(mStockFragment);
        fragments.add(mInformationFragment);
        fragments.add(mUserFragment);
        titles.add("股票");
        titles.add("资讯");
        titles.add("用户");
    }

    private void searchStocks(String SearchText) {
        String url = "http://119.23.221.142/api/stock/SearchStocks?SearchText=" + SearchText;
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                Message message = mHandler.obtainMessage();
                JSONObject object = new JSONObject(s);

                if (object.getString("code").equals("200")) {
                    message.what = SearchStocksSuccess;
                    message.obj = object.getJSONArray("data");
                    mHandler.sendMessage(message);
                } else {
                    message.what = SearchStocksFailed;
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void OnFailed(String s) {

            }
        });
    }

    private void searchUsers(String Username) {
        String url = "http://119.23.221.142/api/user/SearchUsers?Username=" + Username;
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                Message message = mHandler.obtainMessage();
                JSONObject object = new JSONObject(s);

                if (object.getString("code").equals("200")) {
                    message.what = SearchUsersSuccess;
                    message.obj = object.getJSONArray("data");
                    mHandler.sendMessage(message);
                } else {
                    message.what = SearchUsersFailed;
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void OnFailed(String s) {

            }
        });
    }

    private void searchNews(String SearchText) {
        String url = "http://119.23.221.142/api/information/SearchNews?SearchText=" + SearchText;
        OkHttpUtils.getInstance().Get(url, new OkHttpUtils.okHttpListener() {

            @Override
            public void OnSuccess(String s, int code) throws JSONException {
                Message message = mHandler.obtainMessage();
                JSONObject object = new JSONObject(s);
                LogUtils.i("1234:" + s);
                if (object.getString("code").equals("200")) {
                    message.what = SearchNewsSuccess;
                    message.obj = object.getJSONArray("data");
                    mHandler.sendMessage(message);
                } else {
                    message.what = SearchNewsFailed;
                    mHandler.sendMessage(message);
                }
            }

            @Override
            public void OnFailed(String s) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_search_button:
                String input = et_search.getText().toString().trim();
                if (!TextUtils.isEmpty(input)) {
                    if (et_search.getTag().equals("2")) {
                        searchUsers(input);
                        TextView title = mUserFragment.title;
                        title.setText("搜索结果");
                    } else if (et_search.getTag().equals("0")) {
                        searchStocks(input);
                        TextView title = mStockFragment.title;
                        title.setText("搜索结果");
                        LinearLayout start = mStockFragment.stock_start;
                        start.setVisibility(View.GONE);
                    } else if (et_search.getTag().equals("1")) {
                        searchNews(input);
                        TextView title = mInformationFragment.title;
                        title.setText("搜索结果");
                        LinearLayout start = mInformationFragment.start;
                        start.setVisibility(View.GONE);
                    }
                }
                break;
            case R.id.ib_back:
                finish();
        }
    }
}
